package com.nimbusung.gallery;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

/**
 * A Class to handle the URI. 
 * Parses the URIs from the RSS-feeds.  
 * @author Anton Karlsson
 *
 */
public class GalleryConfig {

	private ArrayList<String> gallery_list;

	/**
	 * Constructor
	 */
	public GalleryConfig(){

		//Initilize 
		this.gallery_list = new ArrayList<String>();

	}

	/**
	 * Get the galleryList
	 * @return The current list of the URL
	 */
	public ArrayList<String> getGalleryList(){
		return gallery_list;
	}

	/**
	 * Set the gallerylist 
	 * @param galleryList A list of URIs
	 */
	public void setGalleryList(ArrayList<String> galleryList){
		this.gallery_list = galleryList;
	}


	/**
	 * Parse the JSON-code 
	 * @return ArrayList<String> with all URI
	 */
	public ArrayList<String> fetchPhotos(String url){

		ArrayList<String> listItems = new ArrayList<String>();
		
		try {
			JSONObject json = new JSONObject(getStringContent(url));
			
			JSONArray dataArray = json.getJSONArray("data");
			
			for(int i=0; i < dataArray.length(); i++){

				JSONObject e = dataArray.getJSONObject(i);
				listItems.add(e.getString("source"));

			}
		
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			Log.e("JSON_PICTURES", "Error parsing data " + e.toString());
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return listItems;
		
	}

	/**
	 * Reads the JSON file
	 * @param uri The URI to the file. 
	 * @return A String with the content
	 * @throws Exception 
	 */
	private static String getStringContent(String uri) throws Exception {

		try {
			HttpClient client = new DefaultHttpClient();
			HttpGet request = new HttpGet();
			request.setURI(new URI(uri));
			HttpResponse response = client.execute(request);
			InputStream ips  = response.getEntity().getContent();
			BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));

			StringBuilder sb = new StringBuilder();
			String s;
			while(true )
			{
				s = buf.readLine();
				if(s==null || s.length()==0)
					break;
				sb.append(s);

			}
			buf.close();
			ips.close();
			return sb.toString();

		} 
		finally {
			// any cleanup code...
			// TODO: fix cleanup code.. 
		}
	}

}
